package com.example.xiancheng_handler;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.sql.Time;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity2 extends AppCompatActivity {
    int[] tupian = new int[]{
            R.drawable.img_miao1,R.drawable.img_miao2,R.drawable.img_miao3,R.drawable.img_miao4,
            R.drawable.img_miao5,R.drawable.img_miao6,R.drawable.img_miao7,R.drawable.img_miao8,
            R.drawable.img_miao9,R.drawable.img_miao10,R.drawable.img_miao11,R.drawable.img_miao12,
            R.drawable.img_miao13,R.drawable.img_miao14,R.drawable.img_miao15,R.drawable.img_miao16,
            R.drawable.img_miao17,R.drawable.img_miao18,R.drawable.img_miao19,R.drawable.img_miao20,
            R.drawable.img_miao21,R.drawable.img_miao22,R.drawable.img_miao23,R.drawable.img_miao24,
            R.drawable.img_miao25,R.drawable.img_miao26};
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        init();
    }

    private void init()
    {
        Button button = findViewById(R.id.but_qidong);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击向主线程发送消息
                qidong();
            }
        });
    }
    private void qidong()
    {
        ImageView imageView = findViewById(R.id.img_tu);
        handler = new Handler(Looper.getMainLooper())
        {
            int index = 0;
            //消息处理方法
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                //通过Message.what字段，区分不同来源的消息
                if (msg.what == 1) {
                    imageView.setImageResource(tupian[index++ % tupian.length]);
                }
            }
         };
        new Timer().schedule(new TimerTask()
        {
            @Override
            public void run() {
                handler.obtainMessage(1).sendToTarget();
            }
        },0,100);

    }
}